package com.example.coinhelper.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;

import com.example.coinhelper.Bean.Note;
import com.example.coinhelper.Manage.NoteManager;
import com.example.coinhelper.R;
import com.example.coinhelper.utils.MySesseion;
import com.example.coinhelper.utils.TimeUtility;

import java.util.List;

public class AddNoteActivity extends AppCompatActivity {
    private ImageButton subImaBtn;
    private EditText titleEditText ;
    private EditText contentEditText ;
    private Note note ;
    private NoteManager noteManager;
    private Boolean isUpDate = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_note);
        subImaBtn = findViewById(R.id.note_btn_sub);
        titleEditText = findViewById(R.id.editText2);
        contentEditText = findViewById(R.id.editText3);
        note = new Note();
        InitView();
        noteManager = new NoteManager(this);
        subImaBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = titleEditText.getText().toString();
                String content = contentEditText.getText().toString();
                note.setTitle(title);
                note.setBody(content);
                note.setDate(TimeUtility.getCurrentLocalTime());
                note.setUsername(MySesseion.USER.getUsername());
                if(isUpDate){
                    noteManager.updateNoteById(note);
                }else{
                    noteManager.addNote(note);
                }
                finish();
            }
        });
    }

    private void InitView() {
        Intent intent = getIntent();
        if (intent != null) {

            String title = intent.getStringExtra("title");
            String body = intent.getStringExtra("body");
            String idString = intent.getStringExtra("id");

            // 检查标题是否为空
            if (title != null && !title.isEmpty()) {
                titleEditText.setText(title);
                note.setTitle(title);
            }

            // 检查内容是否为空
            if (body != null && !body.isEmpty()) {
                contentEditText.setText(body);
                note.setBody(body);
            }

            // 检查ID是否为空
            long id = 0; // 默认ID为0
            if (idString != null && !idString.isEmpty()) {
                try {
                    id = Long.parseLong(idString);
                    note.setId(id);
                    isUpDate = true;
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}